package dbLayer;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

import modelLayer.OrderLine;
import modelLayer.SalesOrder;

public class DBSalesOrder implements DBSalesOrderIF {
	
	private Connection con;
	
	public DBSalesOrder() {
		
		this.con = DBConnection.getInstance().getDBcon();
		
	}
	
	@Override
	public int insertOrder(SalesOrder salesOrder) throws Exception {

		int rc = -1;		
		String query = "INSERT INTO SalesOrder (date, deliveryStatus, deliveryDate, customerID, invoiceID) VALUES ('"
				       + salesOrder.getDate().toString()
				       +"','"
				       + salesOrder.getDeliveryStatus()
				       +"','"
				       + salesOrder.getDeliveryDate().toString()
				       +"','"
				       + salesOrder.getCustomer().getCustomerID()
				       +"',"
				       + null
				       + ")";
		System.out.println("insert : " + query);		
		try {
			Statement stmt = this.con.createStatement();
			stmt.setQueryTimeout(5);
			rc = stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);
			// retrieve the generated orderID
			if (rc > 0) {
				System.out.println("SalesOrder inserted.");
				ResultSet idrs = stmt.getGeneratedKeys();
				if (idrs.next()) {
					int id = idrs.getInt(1);
					salesOrder.setOrderID(id);
				}
			}
			stmt.close();
		}
		catch (SQLException ex) {
			System.out.println(ex.getMessage());
			throw new Exception ("Order is not insterted correctly.");
		}		
		insertOrderLines(salesOrder);		
		return rc;
		
	}

	private void insertOrderLines(SalesOrder salesOrder) throws Exception {
		
		DBOrderLine dbOrderLine = new DBOrderLine();
		List<OrderLine> orderLines = salesOrder.getOrderLines();
		for (OrderLine ol : orderLines) {
			dbOrderLine.insertOrderLine(ol);			
		}
		
	}
	
}
